package com.fpx.open.platform.client.web.controller.xms.ae;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.http.MediaType;

import com.fpx.open.platform.common.constant.BaseConstant;

import junit.framework.Assert;

public class HttpTestUtil {
    public static String sendPostRequest(String url, Map<String, String> paraMaps, String contentType) throws Exception {
        HttpPost httpPost = new HttpPost(url);
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        for (Entry<String,String> entry: paraMaps.entrySet()) {
            params.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
        }
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
        String result = sendRequest(httpPost, entity, contentType);
        return result;
    }
	public static String sendHttpGetRequest(HttpGet httpRequest, String mediaType) throws Exception {

		DefaultHttpClient httpClient = new DefaultHttpClient();

		httpRequest.setHeader(HttpHeaders.ACCEPT, mediaType);
		httpRequest.setHeader(HttpHeaders.CONTENT_TYPE,mediaType);
		try {
			ResponseHandler<String> handler = new ResponseHandler<String>() {
				public String handleResponse(HttpResponse response)
						throws ClientProtocolException, IOException {
					HttpEntity httpEntity = null;
					httpEntity = response.getEntity();

					if (httpEntity != null) {
						return EntityUtils.toString(httpEntity, "UTF-8");
					} else {
						return null;
					}
				}
			};

			String result = httpClient.execute(httpRequest, handler);
			
			return result;
		} catch (Exception e) {
			throw new Exception("发送请求服务器端响应出错", e);
		} finally {
			abortRequest(httpRequest);
			shutdown(httpClient);
		}
	}
	
	public static String sendRequest(HttpEntityEnclosingRequestBase httpRequest,
			HttpEntity stringEntity ,String mediaType) throws Exception {

		DefaultHttpClient httpClient = new DefaultHttpClient();

		httpRequest.setHeader(HttpHeaders.ACCEPT, mediaType);
		//httpRequest.setHeader(HttpHeaders.CONTENT_TYPE,mediaType);
	    httpRequest.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded;charset=UTF-8");
		try {
			httpRequest.setEntity(stringEntity);

			ResponseHandler<String> handler = new ResponseHandler<String>() {
				public String handleResponse(HttpResponse response)
						throws ClientProtocolException, IOException {
					HttpEntity httpEntity = null;
					httpEntity = response.getEntity();

					if (httpEntity != null) {
						return EntityUtils.toString(httpEntity, "UTF-8");
					} else {
						return null;
					}
				}
			};

			String result = httpClient.execute(httpRequest, handler);
			
			return result;
		} catch (Exception e) {
			throw new Exception("发送请求服务器端响应出错", e);
		} finally {
			abortRequest(httpRequest);
			shutdown(httpClient);
		}
	}	
	
	public static void shutdown(final HttpClient httpclient) {
		if (httpclient != null) {
			httpclient.getConnectionManager().shutdown();
		}
	}

	public static void abortRequest(final HttpRequestBase hrb) {
		if (hrb != null && hrb.isAborted()) {
			hrb.abort();
		}
	}
	
	public static void testRequestPutAssert(String urlPath, String strReq,
			MediaType mydiaType) throws Exception {

		String result = testRequestPut(urlPath, strReq, mydiaType);
		
		boolean boolResult = false;
		if (MediaType.APPLICATION_JSON.equals(mydiaType)) {
			boolResult = result.contains("\"errorCode\":\"0\"");
		} else {
			boolResult = result.contains("<errorCode>0</errorCode>");
		}

		Assert.assertTrue(boolResult);
	}
	
	public static String testRequestPut(String urlPath, String strReq,
			MediaType mydiaType) throws Exception {
		
		HttpClient httpClient = new DefaultHttpClient();
		// HTTP请求
		HttpPut httpPut = new HttpPut(urlPath);
		
		StringEntity stringEntity = null;
		
		try {
			stringEntity = new StringEntity(strReq, BaseConstant.ENCODE_TYPE);
			String result = HttpTestUtil.sendRequest(httpPut, stringEntity,
					mydiaType.toString());
			System.out.println("返回结果为：" + result);
			return result;
		} finally {
			httpClient.getConnectionManager().shutdown();
		}
	}

	public static void testRequestPostAssert(String urlPath, String strReq,
			MediaType mydiaType) throws Exception {
		
		String result = testRequestPost(urlPath, strReq, mydiaType);
		
		boolean boolResult = false;
		if (MediaType.APPLICATION_JSON.equals(mydiaType)) {
			boolResult = result.contains("\"errorCode\":\"0\"");
		} else {
			boolResult = result.contains("<errorCode>0</errorCode>");
		}
		
		Assert.assertTrue(boolResult);
	}
	
	public static String testRequestPost(String urlPath, String strReq,
			MediaType mydiaType) throws Exception {
		
		HttpClient httpClient = new DefaultHttpClient();
		// HTTP请求
		HttpPost httpPost = new HttpPost(urlPath);
		
		StringEntity stringEntity = null;
		
		try {
			stringEntity = new StringEntity(strReq, BaseConstant.ENCODE_TYPE);
			String result = HttpTestUtil.sendRequest(httpPost, stringEntity,
					mydiaType.toString());
			System.out.println("返回结果为：" + result);
			
		    return result;
		} finally {
			httpClient.getConnectionManager().shutdown();
		}
	}

	public static void testRequestGetAssert(String urlPath, MediaType mydiaType)
			throws Exception {

		String result = testRequestGet(urlPath, mydiaType);
		boolean boolResult = false;
		if (MediaType.APPLICATION_JSON.equals(mydiaType)) {
			boolResult = result.contains("\"errorCode\":\"0\"");
		} else {
			boolResult = result.contains("<errorCode>0</errorCode>");
		}

		Assert.assertTrue(boolResult);
	}
	
	public static String testRequestGet(String urlPath, MediaType mydiaType)
			throws Exception {
		
		HttpGet httpGet = new HttpGet(urlPath);
		httpGet.setHeader("Content-Type", mydiaType.toString());
		httpGet.setHeader("Accept", mydiaType.toString());
		HttpClient httpclient = new DefaultHttpClient();
		HttpResponse response = httpclient.execute(httpGet);
		HttpEntity entity = response.getEntity();
		String result = EntityUtils.toString(entity, BaseConstant.ENCODE_TYPE);
		System.out.println("--result : " + result);
		return result;
	}
}
